export function AutoAdsense(html) {
     const result = { ...html };
     const client = result.client;

     for (const key in result) {
          if (key.startsWith("ad") && result[key]) {
               const value = result[key];
               result[key] = getEachslot(value, client, key);
          }
     }

     let gptScript = `<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-${client}"
     crossorigin="anonymous"></script>`;

     if (result.htmlTest?.trim()) {
          gptScript += `\n${result.htmlTest.trim()}\n`;
     }

     result.htmlTest = gptScript;

     return result;
}

function getEachslot(value, client, key) {
     const isIndexZero = /^ad\d+_0$/.test(key);
     const dataAttr = isIndexZero ? ' data-ad-index="0"' : "";

     return `
     <div class="ad-container"${dataAttr}>
       <div class='gptslot'>
         <ins class="adsbygoogle"
           style="display:inline-block;width:300px;height:250px"
           data-ad-client="ca-pub-${client}"
           data-ad-slot="${value}"></ins>
         <script>
           (adsbygoogle = window.adsbygoogle || []).push({});
         </script>
       </div>
     </div>`;
}


export function parseAdSenseCode(adCode) {
     const cleanedCode = adCode.replace(/""/g, '"');

     const clientMatch = cleanedCode.match(/client=ca-pub-(\d+)/);
     const client = clientMatch ? clientMatch[1] : null;

     const slotMatches = [...cleanedCode.matchAll(/data-ad-slot\s*=\s*["'](\d+)["']/g)];
     const slots = slotMatches.map(m => m[1]);

     const commentMatches = [...cleanedCode.matchAll(/<!--\s*[^>]*?_([\w\d-]+)\s*-->/g)];
     const positions = commentMatches.map(m => m[1]);

     const items = buildItemsMap(positions, slots);
     items.client = client;
     return {
          type: 'autoadsense',
          items
     };
}

function buildItemsMap(positions, slots) {
     const items = {};
     if (!positions || positions.length === 0) {
          const half = Math.ceil(slots.length / 2);
          for (let i = 0; i < slots.length; i++) {
               if (i < half) {
                    items[`ad0_${i}`] = slots[i];
               } else {
                    items[`ad1_${i - half}`] = slots[i];
               }
          }
     } else {
          let homeIndex = 0;
          let detailIndex = 0;
          let unknownIndex = 0;
          let noPosIndex = 0;

          const maxLen = Math.max(positions.length, slots.length);
          for (let i = 0; i < maxLen; i++) {
               const pos = (positions[i] || '').toLowerCase();
               const slot = slots[i];
               if (!slot) continue;

               if (pos.includes('home')) {
                    items[`ad0_${homeIndex++}`] = slot;
               } else if (pos.includes('detail')) {
                    items[`ad1_${detailIndex++}`] = slot;
               } else if (pos.trim() !== '') {
                    items[`ad_unknown_${unknownIndex++}`] = slot;
               } else {
                    items[`ad_no_pos_${noPosIndex++}`] = slot;
               }
          }
     }
     return items;
}


